import 'package:domain/model/article_domain_model.dart';
import 'package:ducafe_ui_core/ducafe_ui_core.dart';
import 'package:feature_main/controller/home_tab_controller.dart';
import 'package:feature_main/feature_config.dart';
import 'package:feature_main/ui/banner/banner_layout.dart';
import 'package:flutter/material.dart';
import 'package:get/get.dart';
import 'package:get_it/get_it.dart';
import 'package:pull_to_refresh/pull_to_refresh.dart';

class HomeTabPage extends StatelessWidget {
  const HomeTabPage({super.key});

  @override
  Widget build(BuildContext context) {
    final tabController = Get.put(
      HomeTabController(
        bannerUseCase: GetIt.I.get(),
        homeArticleUseCase: GetIt.I.get(),
      ),
    );
    WidgetsBinding.instance.addPostFrameCallback((_) {
      tabController.loadData();
    });
    return SafeArea(
      child: GetBuilder(
        init: tabController,
        builder: (controller) {
          return <Widget>[
            BannerLayout(
              bannerModels: controller.banners,
              onClickImage: (String title, String url) {
                final config = GetIt.I.get<MainFeatureConfig>();
                config.navigateToWebview(title, url);
              },
            ),
            Obx(
              () => _createArticleLayout(
                controller: controller.refreshController,
                articles: controller.articles,
                onLoadMore: controller.loadMore,
              ),
            ),
          ].toColumn();
        },
      ),
    );
  }

  Widget _createArticleLayout({
    required RefreshController controller,
    required RxList<ArticleDomainModel> articles,
    required VoidCallback onLoadMore,
  }) => SmartRefresher(
    controller: controller,
    enablePullDown: false,
    enablePullUp: true,
    onLoading: onLoadMore,
    child: ListView.separated(
      itemBuilder: (_, idx) {
        final model = articles[idx];
        return <Widget>[
          SizedBox(height: 10.h),
          <Widget>[
            Spacer(),
            Text(model.publishDate),
          ].toRow(crossAxisAlignment: CrossAxisAlignment.center),
          Text(
            model.title,
            style: TextStyle(color: const Color(0xFF333333), fontSize: 13.sp),
          ),
          SizedBox(height: 10.h),
        ].toColumn(crossAxisAlignment: CrossAxisAlignment.start);
      },
      separatorBuilder: (_, _) => Divider(
        height: 1,
        color: const Color(0xffA0A9B3).withValues(alpha: 0.3),
      ),
      itemCount: articles.length,
    ),
  ).padding(horizontal: 16.w).expanded();
}
